package main

import (
	// "bufio"
	"fmt"
	// "net"
	// "io"
	"os"

	"golang.org/x/net/websocket"
)

var url = "ws://127.0.0.1:8080/"
var origin = "http://127.0.0.1:8080"

//用户信息
var reply []byte

// 账号登录状态
var tre_login bool = false

func main() {

	ws, _ := websocket.Dial(url, "", origin)

	websocket.Message.Send(ws, "setlogin:220")
	websocket.Message.Send(ws, "440")

	websocket.Message.Send(ws, "addSendUsr:330")
	// sendFile("新闻启动页1.png", ws)
	// sendFile("dtwpc.dat", ws)
	// sendFile("Screenshot_20190727_095925.jpg", ws)
	// sendFile("huyanbao_last.exe", ws)
	sendFile("a.png", ws)

	/*
		处理返回数据
	*/
	for {
		//更新用户信息 			理解：错误会返回 信息，此时err值为nil
		if err := websocket.Message.Receive(ws, &reply);
		//不为空，有错误信息
		err != nil {
			return
		}

		//成功返回的标记信息 账号+ok
		if string(reply) == "220ok" {

			tre_login = true
			fmt.Println("等待接收")
			continue
		}

		if tre_login {

		}
	}
	//处理服务器发来的数据

	// main
}

func sendFile(fileName string, ws *websocket.Conn) {

	// fileInfo, _ := os.Stat(fileName)
	file, file_err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	if file_err != nil {

		os.Exit(2)
	}

	for {
		data := make([]byte, 1024)
		count, _ := file.Read(data)

		websocket.Message.Send(ws, data[:count])

		if count <= 0 {
			fmt.Println()
			fmt.Println("数据读取完毕。。")
			break
		}

		fmt.Println(data[:count])

	}

}
